﻿//
// GNS_SetMyInfo.cpp
// GameHall
//
// Created by mr.l on 16/2/3.
//
//

#include "GNS_SetMyInfo.h"
#include "cocostudio/CocoStudio.h"
#include "ui/CocosGUI.h"
#include "GNS_PlayerMgr.h"
#include "GNS_ClientHall.h"
#include "GNS_SceneMgr.h"
#include "SystemMgr.h"	

USING_NS_CC;
using namespace cocostudio::timeline;
using namespace ui;

#define winsize Director::getInstance()->getVisibleSize()


#ifdef WIN32
#define STRCMP(x,y)	_stricmp(x,y)
#define ATOI64(x) _atoi64(x)
#define SNPRINTF(charArray,format,...) _snprintf(charArray,sizeof(charArray)-1,format,__VA_ARGS__)
#else
#define STRCMP(x,y)	strcasecmp(x,y)
#define ATOI64(x) atoll(x)
#define SNPRINTF(charArray,format,...) snprintf(charArray,sizeof(charArray),format,##__VA_ARGS__)
#endif

enum 
{
	BTN_BACK,
	BTN_MYINFO, //自己信息
	BTN_CHANGE_MIMA, //修改密码
	BTN_HEAD,  //编辑头像
	BTN_SUBMIT, //确认修改密码
	BTN_MAN,//男生头像
	BTN_WOMEN,  //女生头像
	BTN_RECOMMEND,		//复制推荐码
};

GNS_SetMyInfo::GNS_SetMyInfo()
{
    pMyInfo=nullptr;
    pPassWord=nullptr;
}

GNS_SetMyInfo::~GNS_SetMyInfo()
{
    
}

GNS_SetMyInfo* GNS_SetMyInfo::createLayer()
{
    auto pGNS_SetMyInfo = GNS_SetMyInfo::create();
    auto pScene = Director::getInstance()->getRunningScene();
    if (!pScene)
        return 0;
    pScene->addChild(pGNS_SetMyInfo);
    return pGNS_SetMyInfo;
}

bool GNS_SetMyInfo::init()
{
    if (!GNS_YJFLayer::init())
    {
        return false;
    }	
    return true;
}
void GNS_SetMyInfo::SetNodeName(std::string CsbName)
{
	m_RootNode = Loadcsb(CsbName);
	addChild(m_RootNode, 11);

	auto pBackBtn = static_cast<Button*>(m_RootNode->getChildByName("Button_4"));
    pBackBtn->setTag(BTN_BACK);
    pBackBtn->addTouchEventListener(CC_CALLBACK_2(GNS_SetMyInfo::BtnCallBack, this));
    
	m_EditNode = static_cast<Node*>(m_RootNode->getChildByName("Node_2"));

	pFaceScrollView = static_cast<ScrollView *>(m_EditNode->getChildByName("FaceScrollView"));
  
	btnMan = static_cast<Button*>(m_EditNode->getChildByName("Button_6"));
	btnMan->addTouchEventListener(CC_CALLBACK_2(GNS_SetMyInfo::BtnCallBack, this));
	btnMan->setTag(BTN_MAN);

	btnwoMan = static_cast<Button*>(m_EditNode->getChildByName("Button_6_0"));
	btnwoMan->addTouchEventListener(CC_CALLBACK_2(GNS_SetMyInfo::BtnCallBack, this));
	btnwoMan->setTag(BTN_WOMEN);
    
	Panel_1 = static_cast<Layout*>(m_RootNode->getChildByName("Panel_1"));
    Panel_1->setVisible(false);
    
    //个人信息
	pUserInfo = static_cast<Button*>(m_RootNode->getChildByName("Button_1"));
    pUserInfo->setTag(BTN_MYINFO);
    pUserInfo->addTouchEventListener(CC_CALLBACK_2(GNS_SetMyInfo::BtnCallBack, this));
    
    //编辑头像
	pEditorFace = static_cast<Button*>(m_RootNode->getChildByName("Button_1_0"));
    pEditorFace->setTag(BTN_HEAD);
    pEditorFace->addTouchEventListener(CC_CALLBACK_2(GNS_SetMyInfo::BtnCallBack, this));
    
    //修改密码
	pModifyPassWord = static_cast<Button*>(m_RootNode->getChildByName("Button_1_0_0"));
    pModifyPassWord->setTag(BTN_CHANGE_MIMA);
    pModifyPassWord->addTouchEventListener(CC_CALLBACK_2(GNS_SetMyInfo::BtnCallBack, this));

	FacebgImage = static_cast<ImageView *>(m_RootNode->getChildByName("Image_33"));
 
	pMyInfo = static_cast<Node*>(m_RootNode->getChildByName("MyInfo"));
	pMyInfo->setVisible(false);

	auto submitBtn = static_cast<Button*>(Panel_1->getChildByName("Button_27"));
	submitBtn->setTag(BTN_SUBMIT);
	submitBtn->addTouchEventListener(CC_CALLBACK_2(GNS_SetMyInfo::BtnCallBack, this));

	auto recommendBtn = static_cast<Button*>(pMyInfo->getChildByName("btn_recommend"));
	//recommendBtn->setVisible(false);
	if (recommendBtn != nullptr)
	{
		recommendBtn->setTag(BTN_RECOMMEND);
		recommendBtn->addTouchEventListener(CC_CALLBACK_2(GNS_SetMyInfo::BtnCallBack, this));
	}

	auto textName = static_cast<TextField*>(pMyInfo->getChildByName("TextField_1"));

	auto listener1 = EventListenerTouchOneByOne::create();
	listener1->onTouchBegan = [](Touch* touch, Event* event)
	{
		auto target = static_cast<TextField*>(event->getCurrentTarget());
		Point locationInNode = target->convertToNodeSpace(touch->getLocation());
		Size s = target->getContentSize();
		Rect rect = Rect(0, 0, s.width, s.height);

		if (!rect.containsPoint(locationInNode))
		{
			log("sprite began... x = %f, y = %f", locationInNode.x, locationInNode.y);
			return true;
		}
		return false;
	};

	listener1->onTouchEnded = [=](Touch* touch, Event* event){
		auto target = static_cast<TextField*>(event->getCurrentTarget());
		if (BTN_MYINFO == m_curPanelType)
		{
			if (m_NameEidt)
			{
				m_NameEidt->onTouchEnded(touch, 0);

				auto strName = UTOG(m_NameEidt->getString().c_str());

				auto gbkName = GNS_PlayerMgr::GetInstance()->getMyNickName();

				if (strName.length()>12)
				{
					ShowCommonTips("超出字符长度！");
					return;
				}

				int res = strcmp(strName.c_str(), gbkName);

				if (0 != res)
				{
					//修改昵称
					CMD_UpdateNickName NickName;
					NickName.lUserID = GNS_PlayerMgr::GetInstance()->getMyUserIdx();
					CCGnsOften::snprintf_safe(NickName.szNickName, 33, strName.c_str(), strName.length());
					GNS_ClientHall::getInstance()->sendData(MAIN_MSG_USER, SUB_CSG_UPD_NICKNAME, (char *)&NickName, sizeof(NickName));
				}
			}
			if (m_phonetext)
			{
				m_phonetext->onTouchEnded(touch, 0);
				auto strPhone = m_phonetext->getString();
				if (0 != strcmp(strPhone.c_str(), GNS_PlayerMgr::GetInstance()->getMyCellPhone()))
				{
					// 修改号码
					CMD_UpdCellPhone cellphone;
					cellphone.lUserId = GNS_PlayerMgr::GetInstance()->getMyUserIdx();
					CCGnsOften::snprintf_safe(cellphone.szNewCellPhone, STR_20_LEN, strPhone.c_str(), strPhone.length());
					GNS_ClientHall::getInstance()->sendData(MAIN_MSG_USER, SUB_CS_UPD_CELLPHONE, (char *)&cellphone, sizeof(cellphone));
					GNS_PlayerMgr::GetInstance()->setMyCellPhone((char*)strPhone.c_str());
				}
			}

			/*if (m_RecommendText)
			{
				m_RecommendText->onTouchEnded(touch, 0);
				auto strRecommend = m_RecommendText->getString();
				if (atoi(strRecommend.c_str()) != GNS_PlayerMgr::GetInstance()->getRecommendCode())
				{
					// 提示不能修改推荐号
					ShowCommonTips("不允许修改推荐号");
					auto str = StringUtils::format("%d", GNS_PlayerMgr::GetInstance()->getRecommendCode());
					m_RecommendText->setString(GTOU(str.c_str()));
				}
			}*/
		}
	};

	_eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, textName);

	ShowInfo(true);
}


bool GNS_SetMyInfo::onTouchBegan(Touch *touch, Event *unused_event)
{
	log("jjjjjjjjjj");
	return true;
}

void GNS_SetMyInfo::onToucheMoved(Touch *touch, Event *unused_event)
{

}

void GNS_SetMyInfo::onTouchEnded(Touch *touch, Event *unused_event)
{
	
}

void GNS_SetMyInfo::BtnCallBack(cocos2d::Ref *pSender, ui::Widget::TouchEventType type){
    if (type==ui::Widget::TouchEventType::ENDED) {
        auto pButton = (Button*)pSender;
        int BtnTag = pButton->getTag();
        switch (BtnTag) {
            case BTN_BACK:
            {
				Show(false);
                break;
            }
            case BTN_MYINFO:
            {
                log("this is MyInfo");
				changeButtonState(BTN_MYINFO);
				m_curPanelType = BTN_MYINFO;
                ShowInfo(true);
                break;
            }
            case BTN_HEAD:
            {
                log("this is Editorface");
				changeButtonState(BTN_HEAD);
				m_curPanelType = BTN_HEAD;
                ShowEditor(true);

				//pFaceScrollView->scrollToTop(0.01, false);
                break;
            }
			case BTN_CHANGE_MIMA:
            {
                log("this is ModifyPassWord");
				changeButtonState(BTN_CHANGE_MIMA);
				m_curPanelType = BTN_CHANGE_MIMA;
                ShowPassWord(true);
                break;
            }
			case BTN_SUBMIT:
			{
				 //确认修改密码
				ChangePassWord();
				break;
			}
			case BTN_WOMEN:
			{
				m_isMan = false;
				btnMan->setBrightStyle(Widget::BrightStyle::NORMAL);
				btnwoMan->setBrightStyle(Widget::BrightStyle::HIGHLIGHT);
				ShowheadType(m_isMan);

				break;
			}
			case BTN_MAN:
			{
				m_isMan = true;
				btnMan->setBrightStyle(Widget::BrightStyle::HIGHLIGHT);
				btnwoMan->setBrightStyle(Widget::BrightStyle::NORMAL);
				ShowheadType(m_isMan);

				break;
			}
			case BTN_RECOMMEND:
			{
#if (CC_TARGET_PLATFORM==CC_PLATFORM_IOS)
				bool IsSuccessful = false;
				auto str = StringUtils::format("%d", GNS_PlayerMgr::GetInstance()->getRecommendCode());
				IsSuccessful = GNS_IOSHelper::GetInstance()->GetClipboard(str);
				if (IsSuccessful == true) {
					ShowCommonTips("复制成功!", Color3B(0, 0, 0), 28);
				}
				else{
					ShowCommonTips("复制失败!", Color3B(0, 0, 0), 28);
				}
#else if(CC_TARGET_PLATFORM==CC_PLATFORM_ANDROID)
				{
					auto str = StringUtils::format("%d", GNS_PlayerMgr::GetInstance()->getRecommendCode());
					SystemMgr::getInstance()->setAndroidClipJNI(str.c_str());
					ShowCommonTips("复制成功!");
				}

#endif
				break;
				/*if (m_RecommendText != nullptr)
					GNS_PlayerMgr::GetInstance()->setRecommendCode(atoi(m_RecommendText->getStringValue().c_str()));
				break;*/
			}
            default:
                break;
        }
		if (BtnTag>=100 && BtnTag<=118)
		{
			  //这里是头像按钮
			// 修改头像
			long long logoId = 0;
			if (m_isMan)
			{
				logoId = BtnTag % 100;
			}
			else
			{
				logoId = 10000 + BtnTag % 100;
			}
			GNS_PlayerMgr::GetInstance()->setMyLogoID(logoId);
			CMD_UpdateUserSyslogoid Syslogoid;
			Syslogoid.lUserID = GNS_PlayerMgr::GetInstance()->getMyUserIdx();
			Syslogoid.lSyslogoid = GNS_PlayerMgr::GetInstance()->getMyLogoID();
			GNS_ClientHall::getInstance()->sendData(MAIN_MSG_USER, SUB_CS_UPD_SYSLOGOID, (char *)&Syslogoid, sizeof(Syslogoid));
			setMylogoFace();
			return;
		}
    }
}

void GNS_SetMyInfo::setMylogoFace()
{
	auto headIm = static_cast<ImageView*>(m_RootNode->getChildByName("Image_1"));
	auto str = StringUtils::format("face_%ld.png", GNS_PlayerMgr::GetInstance()->getMyLogoID());
	headIm->loadTexture(str.c_str());
}


void GNS_SetMyInfo::ShowInfo(bool bShow)
{
    pMyInfo->setVisible(true);
	m_EditNode->setVisible(false);
    Panel_1->setVisible(false);

	m_NameEidt = static_cast<TextField*>(pMyInfo->getChildByName("TextField_1"));

	m_NameEidt->setString(GTOU(GNS_PlayerMgr::GetInstance()->getMyNickName()));
	setMylogoFace();

	auto idtext = static_cast<Text*>(pMyInfo->getChildByName("Text_4"));
	
	string strTmp = StringUtils::toString(GNS_PlayerMgr::GetInstance()->getMyUserIdx());


	idtext->setString(strTmp.c_str());

	//显示手机号码
	m_phonetext = static_cast<TextField*>(pMyInfo->getChildByName("TextField_3"));
	m_phonetext->setString(GTOU(GNS_PlayerMgr::GetInstance()->getMyCellPhone()));

	m_RecommendText = static_cast<Text*>(pMyInfo->getChildByName("Text_2_0_0_0"));
	auto str = StringUtils::format("%d", GNS_PlayerMgr::GetInstance()->getRecommendCode());
	m_RecommendText->setString(GTOU(str.c_str()));
	
	//推荐号为0不显示
	if (GNS_PlayerMgr::GetInstance()->getRecommendCode() == 0)
	{
		m_RecommendText->setString("无");
		auto recommendBtn = static_cast<Button*>(pMyInfo->getChildByName("btn_recommend"));
		recommendBtn->setVisible(false);
	}
	else
	{
		auto recommendBtn = static_cast<Button*>(pMyInfo->getChildByName("btn_recommend"));
		recommendBtn->setVisible(true);
	}
}
void GNS_SetMyInfo::ShowEditor(bool bShow)
{
	m_EditNode->setVisible(true);
    pMyInfo->setVisible(false);
    Panel_1->setVisible(false);
	ShowheadType(m_isMan);
}

void GNS_SetMyInfo::ShowheadType(bool isMan)
{
	for (int i = 0; i < 19; i++)
	{
		//auto str = String::createWithFormat("Button_10_%d", i);
		auto str = "Button_10_";
		auto btnstr = str+StringUtils::toString(i);

		auto btn = static_cast<Button*>(pFaceScrollView->getChildByName(btnstr.c_str()));
		string strname;
		if (m_isMan)
		{
			strname = StringUtils::format("face_%d.png", i);
		}
		else
		{
			strname = StringUtils::format("face_100%02d.png", i);
		}

		btn->addTouchEventListener(CC_CALLBACK_2(GNS_SetMyInfo::BtnCallBack, this));
		btn->setTag(100 + i);
		btn->loadTextures(strname.c_str(), strname.c_str());
	}
}

void GNS_SetMyInfo::ShowPassWord(bool bShow)
{
	m_EditNode->setVisible(false);
    pMyInfo->setVisible(false);
    Panel_1->setVisible(true);

	m_oldpEidt = static_cast<TextField*>(Panel_1->getChildByName("TextField_1"));
	m_NewpEidt = static_cast<TextField*>(Panel_1->getChildByName("TextField_2"));
	m_NewApEidt = static_cast<TextField*>(Panel_1->getChildByName("TextField_3"));
// 	if (m_oldpEidt == nullptr)
// 	{
// 		m_oldpEidt = createEditBox("请输入原始密码", Vec2(332.82, 246.18), 20, Color3B(255, 255, 255), 20);
// 		m_oldpEidt->setContentSize(Size(240, 30));
// 		Panel_1->addChild(m_oldpEidt);
// 	}
// 
// 	if (m_NewpEidt == nullptr)
// 	{
// 		m_NewpEidt = createEditBox("请输入新密码", Vec2(332.82, 184.32), 20, Color3B(255, 255, 255), 20);
// 		m_NewpEidt->setContentSize(Size(240, 30));
// 		Panel_1->addChild(m_NewpEidt);
// 	}
// 
// 	if (m_NewApEidt == nullptr)
// 	{
// 		m_NewApEidt = createEditBox("请确认密码", Vec2(332.82, 119.85), 20, Color3B(255, 255, 255), 20);
// 		m_NewApEidt->setContentSize(Size(240, 30));
// 		Panel_1->addChild(m_NewApEidt);
// 	}
}

void GNS_SetMyInfo::ChangePassWord()
{
	do
	{
		auto strOld = m_oldpEidt->getString();
		if (!strOld.length())
		{
			//m_oldpEidt->attachWithIME();
			ShowCommonTips("原密码不能为空", true);
			//MessageBox("原密码不能为空", "提示");
			break;
		}

		auto pPassNew =m_NewpEidt->getString();
		if (!pPassNew.length())
		{
			//this->showTips(
			ShowCommonTips("新密码不能为空");
			//m_NewpEidt->attachWithIME();
			break;
		}
		
		if (5 > pPassNew.length() || pPassNew.length() > 14)
		{
			//this->showTips(
			ShowCommonTips("新密码长度范围(6 - 14)");
			//MessageBox("新密码长度范围(6 - 14)","提示");
			//m_NewpEidt->attachWithIME();
			break;
		}

		auto pPassNewAgain = m_NewApEidt->getString();
		if (!pPassNewAgain.length())
		{
			//this->showTips(/*新密码不能为空！*/XorStr<0xEC,17,0x582928CB>("\x3C\x2F\x2D\x33\x32\x1A\x40\x48\x30\x29\x38\x5D\x47\x2C\x59\x5A"+0x582928CB).s);
			ShowCommonTips("新密码不能为空");
			//m_NewApEidt->attachWithIME();
			break;
		}
		if (0 != std::strcmp(pPassNew.c_str(), pPassNewAgain.c_str()))
		{
			//this->showTips(/*两次输入的密码不一致！*/XorStr<0x44,23,0xD9A220C9>("\x85\xF8\xF2\x89\x82\xAD\x82\xA0\xF9\x89\x8D\x93\x92\xBA\xE0\xE8\x86\xEE\x80\x95\xFB\xF8"+0xD9A220C9).s);
			ShowCommonTips("两次输入的密码不一致");
			m_NewApEidt->attachWithIME();
			break;
		}

		// 正常流程开始
		//this->showTips(/*正在修改密码 ...*/XorStr<0x28,17,0x98C5B6A7>("\xFD\xD4\xFE\xF1\xFC\xF3\x96\xEB\xF3\xED\xF0\xD8\x14\x1B\x18\x19"+0x98C5B6A7).s);

		CMD_UpdLoginPwd LoginPW;
		LoginPW.lUserId = GNS_PlayerMgr::GetInstance()->getMyUserIdx();
		char PassWord[33] = { 0 };
		memcpy(PassWord, m_oldpEidt->getString().c_str(), 33);
		memcpy(LoginPW.szOldPwd, SystemMgr::getInstance()->md5String(PassWord), 33);
		memcpy(PassWord, m_NewpEidt->getString().c_str(), 33);
		memcpy(LoginPW.szNewPwd, SystemMgr::getInstance()->md5String(PassWord), 33);

		GNS_ClientHall::getInstance()->sendData(MAIN_MSG_USER, SUB_CS_UPD_LOGIN_PWD, (char *)&LoginPW, sizeof(LoginPW));
		return;
	} while (true);
}

void GNS_SetMyInfo::setButtonState()
{
	pUserInfo->setBrightStyle((m_curPanelType == BTN_MYINFO) ? Widget::BrightStyle::HIGHLIGHT : Widget::BrightStyle::NORMAL);
	pEditorFace->setBrightStyle((m_curPanelType == BTN_HEAD) ? Widget::BrightStyle::HIGHLIGHT : Widget::BrightStyle::NORMAL);
	pModifyPassWord->setBrightStyle((m_curPanelType == BTN_CHANGE_MIMA) ? Widget::BrightStyle::HIGHLIGHT : Widget::BrightStyle::NORMAL);
	btnMan->setBrightStyle(m_isMan ? Widget::BrightStyle::HIGHLIGHT : Widget::BrightStyle::NORMAL);
	btnwoMan->setBrightStyle(m_isMan ? Widget::BrightStyle::NORMAL : Widget::BrightStyle::HIGHLIGHT);
}

void GNS_SetMyInfo::changeButtonState(int tag)
{
	pUserInfo->setBrightStyle((tag == pUserInfo->getTag()) ? Widget::BrightStyle::HIGHLIGHT : Widget::BrightStyle::NORMAL);
	pEditorFace->setBrightStyle((tag == pEditorFace->getTag()) ? Widget::BrightStyle::HIGHLIGHT: Widget::BrightStyle::NORMAL);
	pModifyPassWord->setBrightStyle((tag == pModifyPassWord->getTag()) ? Widget::BrightStyle::HIGHLIGHT : Widget::BrightStyle::NORMAL);
}